package org.lemon.db.store;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @since 2024-12-11 12:10
 */
public class Page {
    private ByteBuffer buffer;

    public Page(ByteBuffer buffer) {
        this.buffer = buffer;
    }

    public static Page create(int blockSize) {
        ByteBuffer b = ByteBuffer.allocate(blockSize);
        return new Page(b);
    }

    public static Page create(byte[] bytes) {
        ByteBuffer b = ByteBuffer.wrap(bytes);;
        return new Page(b);
    }

    public void setInt(int offset , int val){
        buffer.putInt(offset,val);
    }

    public int getInt(int offset){
        return buffer.getInt(offset);
    }

    public long getLong(int offset){
        return buffer.getLong(offset);
    }

    public void setLong(int offset , long value){
        buffer.putLong(offset,value);
    }

    public void setBytes(int offset,byte[] bytes){
        buffer.putInt(offset,bytes.length);
        offset = offset + 4;
        for(byte b : bytes){
            buffer.put(offset,b);
            offset++;
        }
    }

    public byte[] getBytes(int offset) {

        int len = buffer.getInt(offset);
        byte[] dst = new byte[len];
        offset += 4;
        for(int i = 0 ; i < len ; i++){
            dst[i] = buffer.get(offset);
            offset++;
        }
        return dst;
    }

    public void setString(int offset,String s){
        byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
        setBytes(offset,bytes);
    }

    public String getString(int offset){
        byte[] bytes = getBytes(offset);
        return new String(bytes,StandardCharsets.UTF_8);
    }

    public int strLen(String s){
        return 4 + s.getBytes(StandardCharsets.UTF_8).length;
    }

    public int blen(byte[] bytes){
        return  4 + bytes.length;
    }

    public ByteBuffer buffer(){
        return buffer;
    }

    public void reset(){
        buffer.rewind();
    }


}
